import React, {useRef,useState,useEffect} from 'react'
import {useSearchParams} from "react-router-dom";
import { Card, Grid,Button,Selector,CalendarPicker } from 'antd-mobile'
import * as echarts from "echarts"
import dayjs from 'dayjs'
import {PracticeApi} from '@api/index'

import './index.less'

const min = new Date()
min.setMonth(min.getMonth() - 12)

export default ()=> {

    const chartRef = useRef()
    const [start, setStart] = useState(dayjs().add(-7, 'd').format('YYYY-MM-DD'))
    const [end, setEnd] = useState(dayjs().format('YYYY-MM-DD'))
    const [type, setType] = useState("1")
    const [squatTimes, setSquatTimes] = useState(0)
    const [deadliftTimes, setDeadliftTimes] = useState(0)
    const [benchPressTimes, setBenchPressTimes] = useState(0)
    const [visible, setVisible] = useState(false)
    const [searchParams] = useSearchParams();
    const token = searchParams.get('token');


    const options = [
        {
            label: '日',
            value: 1,
        },
        {
            label: '周',
            value: 2,
        },
        {
            label: '月',
            value: 3,
        },
    ]

    const statTime = async () => {
        sessionStorage.setItem("user_token",token)
        let params={"start": start, "end": end, "type": type}
        let ret = await PracticeApi.statTime(params)
        if (ret && ret.code === 200) {

            let data=ret.data
            setSquatTimes(data.squatTimes)
            setDeadliftTimes(data.deadliftTimes)
            setBenchPressTimes(data.benchPressTimes)

            let dataset = []
            let arr0=[]
            let arr1=[]
            let arr2=[]
            let arr3=[]
            for (let i = 0; i < ret.data.list.length; i++) {
                let item = ret.data.list[i]
                arr0.push([item.day, item.duration])
                arr1.push([item.day, item.squatTimes])
                arr2.push([item.day, item.deadliftTimes])
                arr3.push([item.day, item.benchPressTimes])
            }
            dataset.push({
                dimensions:["day","duration"],
                source:arr0
            })
            dataset.push({
                dimensions:["day","squatTimes"],
                source:arr1
            })

            dataset.push({
                dimensions:["day","deadliftTimes"],
                source:arr2
            })

            dataset.push({
                dimensions:["day","benchPressTimes"],
                source:arr3
            })

            chartRef.current.setOption({
                dataset:dataset
            })
        }
    }

    const initChart = async () => {
        chartRef.current = echarts.init(document.getElementById("order-stat-growth"));
        chartRef.current.setOption({
            legend: {},
            tooltip: {
                show: true,
                formatter:function (params) {
                    if(params.seriesIndex==0) {
                        let name= params.value[0]
                        let value= Math.floor(params.value[1]/60)
                        return params.seriesName+'<br>' + name+" "+value +"分钟"
                    }
                    return params.seriesName+'<br>' + params.value.join(" ")
                }
            },

            xAxis: {
                type: 'category'
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                name: '训练时长',
                type: 'line',
                encode: {x: 'day', y: 'duration'},
                datasetIndex: 0
            },
                {
                    name: '深蹲次数',
                    type: 'bar',
                    stack: 'b',
                    barMaxWidth:40,
                    encode: {x: 'day', y: 'squatTimes'},
                    datasetIndex: 1
                },
                {
                    name: '硬拉次数',
                    type: 'bar',
                    stack: 'b',
                    barMaxWidth:40,
                    encode: {x: 'day', y: 'deadliftTimes'},
                    datasetIndex: 2
                },
                {
                    name: '卧推次数',
                    type: 'bar',
                    stack: 'b',
                    barMaxWidth:40,
                    encode: {x: 'day', y: 'benchPressTimes'},
                    datasetIndex: 3
                }
            ],
        });
    }

    const hander = () => {
        chartRef.current.resize()
    }

    useEffect(() => {
        initChart()
        window.addEventListener("resize", hander)
        return () => {
            window.removeEventListener('resize', hander)
        }
    }, [])

    useEffect(() => {
        statTime()
    }, [start, end,type])

    const onChangeType = (value) => {
        setType(value)
    };

    const toChangePeriod=()=>{
        setVisible(true)
    }

    const changePeriod=(peroid)=>{
        let pStart=dayjs(peroid[0]).format('YYYY-MM-DD')
        let pEnd=dayjs(peroid[1]).format('YYYY-MM-DD')
        setStart(pStart)
        setEnd(pEnd)
    }


    return (
        <>
            <div className="num-wraper">
                <Selector
                    columns={3}
                    options={options}
                    defaultValue={[1]}
                    onChange={(arr, extend) => onChangeType(arr[0])}
                />
            </div>
            <div className="num-wraper">
                <Button block onClick={toChangePeriod}>
                    {start} 至 {end}
                </Button>
            </div>
            <div className="num-wraper">
                <Grid columns={3} gap={8}>
                    <Grid.Item>
                        <Card className="stat-card" title='深蹲'>
                            <h3 align="center">{squatTimes}</h3>
                        </Card>
                    </Grid.Item>
                    <Grid.Item>
                        <Card className="stat-card" title='硬拉'>
                            <h3 align="center">{deadliftTimes}</h3>
                        </Card>
                    </Grid.Item>
                    <Grid.Item>
                        <Card className="stat-card" title='卧推'>
                            <h3 align="center">{benchPressTimes}</h3>
                        </Card>
                    </Grid.Item>
                </Grid>
            </div>
            <div className="num-wraper">
                <div id="order-stat-growth" style={{width: '100%', height: 400, border: "1px solid #f0f0f0"}}></div>
            </div>
            <CalendarPicker
                min={min}
                visible={visible}
                defaultValue={[start,end]}
                selectionMode='range'
                onClose={() => setVisible(false)}
                onMaskClick={() => setVisible(false)}
                onConfirm={val => {
                    changePeriod(val)
                }}
            />

        </>
    )
}
